package com.mdd.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mdd.common.R;
import com.mdd.pojo.Voucher;
import com.mdd.pojo.request.VoucherAddRequest;
import com.mdd.pojo.request.VoucherPageRequest;
import com.mdd.pojo.request.VoucherUpdateRequest;
import com.mdd.service.VoucherService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/voucher")
public class VoucherController {

    @Autowired
    private VoucherService voucherService;

    /**
     * 添加优惠券/秒杀券
     * @param voucherAddRequest
     * @return
     */
    @CacheEvict(value = "voucherCache",allEntries = true)
    @PostMapping("/add")
    public R<String> addVoucher(@RequestBody VoucherAddRequest voucherAddRequest){
        //校验
        if (voucherAddRequest == null) {
            return R.error("添加失败");
        }
        //添加
        return voucherService.addVoucher(voucherAddRequest);
    }

    /**
     * 删除优惠券
     * @param id
     * @return
     */
    @CacheEvict(value = "voucherCache",allEntries = true)
    @DeleteMapping("/delete")
    public R<String> delVoucher(@RequestParam("id") Long id){
        if (id == null) {
            return R.error("删除失败");
        }
        if (voucherService.removeById(id)) {
            return R.success("删除成功");
        }
        return R.error("删除失败");
    }

    /**
     * 修改优惠券信息
     * @param voucherUpdateRequest
     * @return
     */
    @PutMapping("/update")
    @CacheEvict(value = "voucherCache",allEntries = true)
    public R<String> updateVoucher(@RequestBody VoucherUpdateRequest voucherUpdateRequest){
        //进行检验
        if (voucherUpdateRequest == null) {
            return R.error("没有数据");
        }
        return voucherService.updateVoucher(voucherUpdateRequest);
    }


    /**
     * 分页查询(条件)
     * @param voucherPageRequest
     * @return
     */
    @GetMapping("/page")
    @Cacheable(value = "voucherCache",key = "#voucherPageRequest.page+'_'+#voucherPageRequest.pageSize")
    public R<Page<Voucher>> showVoucherList(VoucherPageRequest voucherPageRequest){
        //校验
        if (voucherService == null) {
            return R.error("展示失败");
        }
        return voucherService.voucherPage(voucherPageRequest);

    }
}
